import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/utils/api'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  
  // 登录
  const login = async (loginData) => {
    try {
      const response = await api.post('/auth/login', loginData)
      if (response.data.success) {
        const { token: newToken, ...user } = response.data.data
        token.value = newToken
        userInfo.value = user
        
        // 保存到本地存储
        localStorage.setItem('token', newToken)
        localStorage.setItem('userInfo', JSON.stringify(user))
        
        // 设置API默认请求头
        api.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
        
        return { success: true }
      } else {
        return { success: false, message: response.data.message }
      }
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.message || '登录失败' 
      }
    }
  }
  
  // 注册
  const register = async (registerData) => {
    try {
      const response = await api.post('/auth/register', registerData)
      return {
        success: response.data.success,
        message: response.data.message
      }
    } catch (error) {
      return {
        success: false,
        message: error.response?.data?.message || '注册失败'
      }
    }
  }
  
  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    
    // 清除API请求头
    delete api.defaults.headers.common['Authorization']
  }
  
  // 初始化时设置请求头
  if (token.value) {
    api.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
  }
  
  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    register,
    logout
  }
}) 